package com.likl.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.likl.controller.utils.R;
import com.likl.domain.Book;
import com.likl.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * ClassName:springboot_study
 * Description:
 *
 * @Create: 2024/7/2 14:14
 * @author: likl
 * @e-mail: likl1102@foxmail.com
 * @QQ: 2514927731
 */
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private IBookService iBookService;

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        return new R(true, iBookService.getById(id));
    }

    @GetMapping()
    public R getAll() {
        return new R(true, iBookService.list());
    }

    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        if (true) {
            throw new IOException();
        }
        return new R(iBookService.save(book));
    }

    @PutMapping
    public R update(@RequestBody Book book) {
        return new R(iBookService.updateById(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        return new R(iBookService.removeById(id));
    }

//    @GetMapping("{currentPage}/{pageSize}")
//    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize) {
//        IPage<Book> page = iBookService.getPage(currentPage, pageSize);
//        // 如果当前页码大于了总页码值，那么重新执行查询操作，使用最大页码值进行查询
//        if (currentPage > page.getPages()) {
//            page = iBookService.getPage((int) page.getPages(), pageSize);
//        }
//        return new R(true, page);
//    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Book book) {
        IPage<Book> page = iBookService.getPage(currentPage, pageSize, book);
        // 如果当前页码大于了总页码值，那么重新执行查询操作，使用最大页码值进行查询
        if (currentPage > page.getPages()) {
            page = iBookService.getPage((int) page.getPages(), pageSize, book);
        }
        return new R(true, page);
    }
}
